<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\middleware\Auth;
use app\BaseController;
use think\facade\View;
use app\common\model\Config as ConfigModel;

class Config extends BaseController
{
    protected $middleware = [
        Auth::class
    ];

    public function index()
    {
        if($this->request->isPost())
        {
            // 接收所有的参数
            $params = $this->request->param();

            // 获取参数名重新弄一个新的一维数组
            $KeyList = array_keys($params);

            // 查询所有的数据
            $list = ConfigModel::column('key,id');

            // 封装更新的数组
            $ConfigData = [];

            foreach($list as $item)
            {
                // 判断是否一样的key
                if(in_array($item['key'],$KeyList))
                {
                    $ConfigData[] = [
                        'id' => $item['id'],
                        'value' => $params[$item['key']]
                    ];
                }
            }

            // 定义一个配置各种图片数组
            $FileData = [];

            // 判断是否有logo上传
            if(!empty($_FILES))
            {
                $FileKey = array_keys($_FILES);

                foreach($list as $item)
                {
                    if(in_array($item['key'],$FileKey))
                    {
                        $Logo = upload($item['key']);

                        if($Logo['code'] == 1)
                        {
                            $file = ConfigModel::find($item['id']);

                            $FileData[] = $file;

                            @is_file('.'.$file['value']) && @unlink('.'.$file['value']);
                            
                            $ConfigData[] = [
                                'id' => $item['id'],
                                'value' => '/'.$Logo['data']
                            ];
                        }
                    }
                }
            }

            $ConfigModel = new ConfigModel();

            $result = $ConfigModel->saveAll($ConfigData);

            if($result)
            {
                $this->success('更新配置成功');
            }else{
                foreach($FileData as $item)
                {
                    @is_file('.'.$item['value']) && @unlink('.'.$item['value']);
                }
                $this->error('更新配置失败');
            }

        }

        $nav_title = [
            'nav_title' => '系统配置',
            'title' => '系统配置'
        ];

        // 查询配置数据
        $ConfigList = ConfigModel::select();

        return View::fetch('',[
            'nav_title' => $nav_title,
            'ConfigList' => $ConfigList
        ]);
    }
}
